import React from 'react';
class RootSiblings extends React.Component {
	state = { siblings: {} };
	static instance: RootSiblings;

	constructor(props: any) {
		super(props);
		RootSiblings.instance = this;
	}
	static destorySibling(id: string) {
		let siblings = { ...RootSiblings.instance.state.siblings };
		delete siblings[id];
		RootSiblings.instance.setState({ siblings });
	}
	static addSibling(id: string, TopComponent: JSX.Element) {
		let siblings = { ...RootSiblings.instance.state.siblings };
		siblings[id] = TopComponent;
		RootSiblings.instance.setState({ siblings });
	}
	render() {
		let { siblings } = this.state;
		let elements = Object.keys(siblings).map(id => {
			return siblings[id];
		});
		return elements;
	}
}
export const TopViewProvider: React.FC = props => {
	return (
		<React.Fragment>
			{props.children}
			<RootSiblings />
		</React.Fragment>
	);
};

let uuid = 0;

export interface TopViewProps {
	destroy(): void;
}
export function addTopView(TopComponent: React.ComponentType<TopViewProps>) {
	let id = uuid++;
	let destroy = () => {
		RootSiblings.destorySibling(id.toString());
	};
	let element = <TopComponent key={id.toString()} destroy={destroy} />;
	RootSiblings.addSibling(id.toString(), element);
}
